import request from '@/utils/request'
import type { ApiResponse } from '@/types/common'
import type {
  Message,
  Msg,
  Statistics,
  HomeStatistics,
  TaskData,
  ActivityData,
  DashboardStats,
} from '@/types/home'

// 不再需要单独的空响应生成函数，直接在方法中返回简化的数据结构

// 首页相关API接口定义
export const homeApi = {
  // 获取首页统计数据
  getHomeStatistics: (): Promise<ApiResponse<HomeStatistics>> => {
    return request({
      url: '/api/home/index/main',
      method: 'get',
    })
      .then(axiosResponse => {
        // 处理AxiosResponse，提取data部分
        return axiosResponse.data as ApiResponse<HomeStatistics>
      })
      .catch(error => {
        // 返回符合HomeStatistics类型的默认数据作为兜底
        return {
          code: 0,
          msg: 'success',
          data: {
            total: [],
            finance: [],
            business: {},
            todue: [],
            schedule: [],
            tasks: [],
            dynamics: [],
          },
        } as ApiResponse<HomeStatistics>
      })
  },

  // 获取Dashboard统计数据（简化版）
  getDashboardStats: (): Promise<ApiResponse<DashboardStats>> => {
    return request({
      url: '/api/home/dashboard/stats',
      method: 'get',
    })
      .then((response: any) => {
        // 检查响应格式
        if (response && response.code === 0 && response.data) {
          return response
        }

        // 返回空的标准响应
        return {
          code: 0,
          msg: 'success',
          data: {
            user_info: {
              id: 0,
              name: '',
              dept_name: '',
              position_name: '',
            },
            quick_actions: [],
            permissions: {
              is_leader: false,
              department_count: 0,
              can_approve: false,
              permission_level: 'staff',
            },
            stats: {
              overview: [],
              finance: [],
              business: [],
              pending: [],
              schedule: {},
              messages: {},
              comprehensive: {},
            },
            summary: {
              total_items: 0,
              pending_count: 0,
              unread_count: 0,
            },
            last_update: 0,
          },
          timestamp: Date.now(),
        }
      })
      .catch(error => {
        // 错误处理简化
        // 返回空的标准响应
        return {
          code: 0,
          msg: 'success',
          data: {
            user_info: {
              id: 0,
              name: '',
              dept_name: '',
              position_name: '',
            },
            quick_actions: [],
            permissions: {
              is_leader: false,
              department_count: 0,
              can_approve: false,
              permission_level: 'staff',
            },
            stats: {
              overview: [],
              finance: [],
              business: [],
              pending: [],
              schedule: {},
              messages: {},
              comprehensive: {},
            },
            summary: {
              total_items: 0,
              pending_count: 0,
              unread_count: 0,
            },
            last_update: 0,
          },
          timestamp: Date.now(),
        }
      })
  },

  // 获取未读消息统计
  getUnreadStatistics: (): Promise<ApiResponse<Statistics>> => {
    return request({
      url: '/api/home/index/index',
      method: 'get',
    })
      .then(axiosResponse => {
        // 处理AxiosResponse，提取data部分
        return axiosResponse.data as ApiResponse<Statistics>
      })
      .catch(error => {
        // 使用0值数据代替模拟数据
        return {
          code: 0,
          msg: 'success',
          data: {
            msg_num: 0,
            total: 0,
            unread: 0,
            read: 0,
          },
        } as ApiResponse<Statistics>
      })
  },

  // 获取收件箱列表
  getInboxList: (params: any): Promise<ApiResponse<Msg[]>> => {
    return request({
      url: '/api/home/message/inbox',
      method: 'get',
      params,
    })
  },

  // 获取发件箱列表
  getSendboxList: (params: any): Promise<ApiResponse<Message[]>> => {
    return request({
      url: '/api/home/message/sendbox',
      method: 'get',
      params,
    })
  },

  // 获取草稿箱列表
  getDraftList: (params: any): Promise<ApiResponse<Message[]>> => {
    return request({
      url: '/api/home/message/draft',
      method: 'get',
      params,
    })
  },

  // 获取星标信息列表
  getStarList: (params: any): Promise<ApiResponse<Msg[]>> => {
    return request({
      url: '/api/home/message/star',
      method: 'get',
      params,
    })
  },

  // 获取垃圾箱列表
  getRubbishList: (params: any): Promise<ApiResponse<any[]>> => {
    return request({
      url: '/api/home/message/rubbish',
      method: 'get',
      params,
    })
  },

  // 查看收件
  readMsg: (id: number): Promise<ApiResponse<Msg>> => {
    return request({
      url: `/home/message/read/${id}`,
      method: 'get',
    })
  },

  // 查看发件
  viewMessage: (id: number): Promise<ApiResponse<Message>> => {
    return request({
      url: `/home/message/view/${id}`,
      method: 'get',
    })
  },

  // 新增/编辑信息
  saveMessage: (data: any) => {
    return request({
      url: '/api/home/message/save',
      method: 'post',
      data,
    })
  },

  // 发送消息
  sendMessage: (id: number) => {
    return request({
      url: `/home/message/send_message/${id}`,
      method: 'post',
    })
  },

  // 删除发件、草稿
  deleteMessage: (data: any) => {
    return request({
      url: '/api/home/message/del',
      method: 'post',
      data,
    })
  },

  // 状态修改
  updateMsgStatus: (data: any) => {
    return request({
      url: '/api/home/message/check',
      method: 'post',
      data,
    })
  },

  // 还原消息
  recoveryMessage: (data: any) => {
    return request({
      url: '/api/home/message/recovery',
      method: 'post',
      data,
    })
  },

  // 清除消息
  clearMessage: (data: any) => {
    return request({
      url: '/api/home/message/clear',
      method: 'post',
      data,
    })
  },

  // 修改个人信息
  editPersonal: (data: any) => {
    return request({
      url: '/api/home/index/edit_personal',
      method: 'post',
      data,
    })
  },

  // 获取任务列表数据
  getTaskList: (): Promise<ApiResponse<TaskData[]>> => {
    return request({
      url: '/api/task/list',
      method: 'get',
    })
      .then(axiosResponse => {
        // 处理AxiosResponse，提取data部分
        return axiosResponse.data as ApiResponse<TaskData[]>
      })
      .catch(error => {
        // 使用空数组代替模拟数据
        return {
          code: 0,
          msg: 'success',
          data: [],
          count: 0,
        } as ApiResponse<TaskData[]>
      })
  },

  // 获取最新动态数据
  getLatestActivities: (): Promise<ApiResponse<ActivityData[]>> => {
    return request({
      url: '/api/home/activities/latest',
      method: 'get',
    })
      .then(axiosResponse => {
        // 处理AxiosResponse，提取data部分
        return axiosResponse.data as ApiResponse<ActivityData[]>
      })
      .catch(error => {
        // 使用空数组代替模拟数据
        return {
          code: 0,
          msg: 'success',
          data: [],
          count: 0,
        } as ApiResponse<ActivityData[]>
      })
  },

  // 获取审批数据
  getApprovalList: (): Promise<ApiResponse<any[]>> => {
    return request({
      url: '/api/approval/list',
      method: 'get',
    })
      .then(axiosResponse => {
        // 处理AxiosResponse，提取data部分
        return axiosResponse.data as ApiResponse<any[]>
      })
      .catch(error => {
        // 使用空数组代替模拟数据
        return {
          code: 0,
          msg: 'success',
          data: [],
          count: 0,
        } as ApiResponse<any[]>
      })
  },

  // 修改密码
  editPassword: (data: any) => {
    return request({
      url: '/api/home/index/edit_password',
      method: 'post',
      data,
    })
  },

  // 地区管理相关接口（从 home/area.ts 合并）
  // 获取全国省市列表
  getAreaList: (params?: any) => {
    return request({
      url: '/api/system/region/list',
      method: 'get',
      params,
    })
  },

  // 新增/编辑全国省市
  saveArea: (data: any) => {
    // 根据是否有id判断是新增还是编辑
    if (data.id) {
      return request({
        url: '/api/system/region/edit',
        method: 'post',
        data,
      })
    } else {
      return request({
        url: '/api/system/region/add',
        method: 'post',
        data,
      })
    }
  },

  // 设置地区状态（启用/禁用）
  setAreaStatus: (data: { id: number; status: number }) => {
    return request({
      url: '/api/system/region/set_status',
      method: 'post',
      data,
    })
  },

  // 获取地区列表用于下拉选择
  getAreaOptions: (params?: any) => {
    return request({
      url: '/api/system/region',
      method: 'get',
      params,
    })
  },

  // 获取启用地区列表（树形结构）
  getActiveAreaTree: (params?: any) => {
    return request({
      url: '/api/system/region/set',
      method: 'get',
      params,
    })
  },

  // 删除地区
  deleteArea: (id: number) => {
    return request({
      url: '/api/system/region/del',
      method: 'post',
      data: { id },
    })
  },

  // 查看地区详情
  viewArea: (id: number) => {
    return request({
      url: '/api/system/region/view',
      method: 'get',
      params: { id },
    })
  },

  // 企业主体管理相关接口（从 home/cate.ts 合并）
  // 获取企业主体列表
  getEnterpriseList: (params?: any) => {
    return request({
      url: '/api/home/cate/enterprise/list',
      method: 'get',
      params,
    })
  },

  // 新增/编辑企业主体
  saveEnterprise: (data: any) => {
    return request({
      url: '/api/home/cate/enterprise_add',
      method: 'post',
      data,
    })
  },

  // 设置企业主体状态（启用/禁用）
  setEnterpriseStatus: (data: any) => {
    return request({
      url: '/api/home/cate/enterprise_check',
      method: 'post',
      data,
    })
  },

  // 配置管理相关接口（从 home/conf.ts 合并）
  // 获取配置项列表
  getConfigList: (params?: any) => {
    return request({
      url: '/api/home/conf/list',
      method: 'get',
      params,
    })
  },

  // 新增/编辑配置项
  saveConfig: (data: any) => {
    return request({
      url: '/api/home/conf/add',
      method: 'post',
      data,
    })
  },

  // 删除配置项
  deleteConfig: (data: any) => {
    return request({
      url: '/api/home/conf/del',
      method: 'delete',
      data,
    })
  },

  // 编辑配置详情
  editConfig: (data: any) => {
    return request({
      url: '/api/home/conf/edit',
      method: 'put',
      data,
    })
  },

  // 数据权限管理相关接口（从 home/dataauth.ts 合并）
  // 获取模块配置列表
  getDataAuthList: (params?: any) => {
    return request({
      url: '/api/home/dataauth/list', // 修正API路径，与后端路由配置保持一致
      method: 'get',
      params,
    })
  },

  // 编辑模块配置
  editDataAuth: (data: any) => {
    return request({
      url: '/api/home/dataauth/edit',
      method: 'post',
      data,
    })
  },

  // 数据库管理相关接口（从 home/database.ts 合并）
  // 获取数据表列表
  getDatabaseTables: (params?: any) => {
    return request({
      url: '/api/home/database/list',
      method: 'get',
      params,
    })
  },

  // 获取备份文件列表
  getBackupList: (params?: any) => {
    return request({
      url: '/api/home/database/backup_list',
      method: 'get',
      params,
    })
  },

  // 备份数据表
  backupTables: (data: any) => {
    return request({
      url: '/api/home/database/backup',
      method: 'post',
      data,
    })
  },

  // 优化数据表
  optimizeTables: (data: any) => {
    return request({
      url: '/api/home/database/optimize',
      method: 'post',
      data,
    })
  },

  // 修复数据表
  repairTables: (data: any) => {
    return request({
      url: '/api/home/database/repair',
      method: 'post',
      data,
    })
  },

  // 还原数据表
  importBackup: (data: any) => {
    return request({
      url: '/api/home/database/restore',
      method: 'post',
      data,
    })
  },

  // 下载备份数据
  downloadBackup: (params: any) => {
    return request({
      url: '/api/home/database/downfile',
      method: 'get',
      params,
    })
  },

  // 删除备份数据
  deleteBackup: (data: any) => {
    return request({
      url: '/api/home/database/del',
      method: 'delete',
      data,
    })
  },

  // 规则管理相关接口（从 home/rule.ts 合并）
  // 获取规则列表
  getRuleList: (params?: any) => {
    return request({
      url: '/api/home/rule/rule_list',
      method: 'get',
      params,
    })
  },

  // 获取菜单规则列表
  getMenuRuleList: (params?: any) => {
    return request({
      url: '/api/home/rule/rule_list',
      method: 'get',
      params,
    })
  },

  // 查看功能节点详情
  viewRule: (params?: any) => {
    return request({
      url: '/api/home/rule/rule_view',
      method: 'get',
      params,
    })
  },

  // 新增功能节点
  addRule: (data: any) => {
    return request({
      url: '/api/home/rule/rule_add',
      method: 'post',
      data,
    })
  },

  // 编辑功能节点
  editRule: (data: any) => {
    return request({
      url: '/api/home/rule/rule_edit',
      method: 'put',
      data,
    })
  },

  // 删除功能节点
  deleteRule: (data: any) => {
    return request({
      url: '/api/home/rule/rule_del',
      method: 'delete',
      data,
    })
  },

  // 定时任务相关接口（从 home/task.ts 合并）
  // 获取定时任务列表
  getScheduleTaskList: (params?: any) => {
    // 重命名函数以避免冲突
    return request({
      url: '/api/home/task/list',
      method: 'get',
      params,
    })
  },

  // 新增/编辑定时任务
  saveTask: (data: any) => {
    return request({
      url: '/api/home/task/add',
      method: 'post',
      data,
    })
  },

  // 删除定时任务
  deleteTask: (data: any) => {
    return request({
      url: '/api/home/task/del',
      method: 'delete',
      data,
    })
  },

  // 消息模板相关接口（从 home/template.ts 合并）
  // 获取消息模板列表
  getTemplateList: (params?: any) => {
    return request({
      url: '/api/home/template/datalist',
      method: 'get',
      params,
    })
  },

  // 新增/编辑消息模板
  saveTemplate: (data: any) => {
    return request({
      url: '/api/home/template/add',
      method: 'post',
      data,
    })
  },

  // 设置消息模板状态
  setTemplateStatus: (data: any) => {
    return request({
      url: '/api/home/template/set',
      method: 'post',
      data,
    })
  },

  // 查看消息模板
  viewTemplate: (params?: any) => {
    return request({
      url: '/api/home/template/view',
      method: 'get',
      params,
    })
  },

  // 删除消息模板
  deleteTemplate: (data: any) => {
    return request({
      url: '/api/home/template/del',
      method: 'post',
      data,
    })
  },

  // 功能模块管理相关接口
  // 获取功能模块列表
  getModuleList: (params?: any) => {
    return request({
      url: '/api/home/module/list',
      method: 'get',
      params,
    })
  },

  // 查看功能模块详情
  viewModule: (params?: any) => {
    return request({
      url: '/api/home/module/view',
      method: 'get',
      params,
    })
  },

  // 新增功能模块
  saveModule: (data: any) => {
    return request({
      url: '/api/home/module/add',
      method: 'post',
      data,
    })
  },

  // 编辑功能模块
  editModule: (data: any) => {
    return request({
      url: '/api/home/module/edit',
      method: 'put',
      data,
    })
  },

  // 删除功能模块
  deleteModule: (data: any) => {
    return request({
      url: '/api/home/module/del',
      method: 'delete',
      data,
    })
  },

  // 启用/禁用功能模块
  toggleModuleStatus: (data: any) => {
    return request({
      url: '/api/home/module/toggle_status',
      method: 'post',
      data,
    })
  },

  // 恢复功能模块
  restoreModule: (data: any) => {
    return request({
      url: '/api/home/module/recovery',
      method: 'post',
      data,
    })
  },

  // 安装功能模块
  installModule: (data: any) => {
    return request({
      url: '/api/home/module/install',
      method: 'post',
      data,
    })
  },
}
